#!/usr/bin/env python3
"""直接测试MCP服务器的stdio通信"""

import subprocess
import json
import time
import sys

def test_direct_stdio():
    """直接测试stdio通信"""
    print("开始直接stdio测试...")
    
    try:
        # 启动MCP服务器
        process = subprocess.Popen(
            [sys.executable, "main.py", "--mode", "stdio", "--config", "config"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            cwd="d:\\MCP\\mcp2",
            env={"PYTHONPATH": "d:\\MCP\\mcp2"}
        )
        
        print(f"✅ MCP服务器已启动，进程ID: {process.pid}")
        
        # 等待服务器启动
        time.sleep(2)
        
        # 检查进程是否还在运行
        if process.poll() is not None:
            stdout, stderr = process.communicate()
            print(f"❌ 服务器启动失败")
            print(f"STDOUT: {stdout}")
            print(f"STDERR: {stderr}")
            return False
        
        print("✅ 服务器正在运行")
        
        # 发送初始化请求
        init_request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {
                    "name": "direct-test-client",
                    "version": "1.0.0"
                }
            }
        }
        
        request_str = json.dumps(init_request) + "\n"
        print(f"发送请求: {request_str.strip()}")
        
        # 发送请求
        process.stdin.write(request_str)
        process.stdin.flush()
        
        print("等待响应...")
        
        # 设置超时读取响应
        import select
        import os
        
        if os.name == 'nt':  # Windows
            # Windows上使用简单的超时机制
            start_time = time.time()
            response = None
            
            while time.time() - start_time < 10:  # 10秒超时
                if process.poll() is not None:
                    print("❌ 服务器进程已退出")
                    break
                
                # 尝试读取输出
                try:
                    # 非阻塞读取
                    import msvcrt
                    if msvcrt.kbhit() or process.stdout.readable():
                        line = process.stdout.readline()
                        if line:
                            response = line.strip()
                            break
                except:
                    pass
                
                time.sleep(0.1)
        else:
            # Unix系统使用select
            ready, _, _ = select.select([process.stdout], [], [], 10)
            if ready:
                response = process.stdout.readline().strip()
        
        if response:
            print(f"✅ 收到响应: {response}")
            try:
                response_data = json.loads(response)
                if 'result' in response_data:
                    print("✅ 初始化成功!")
                    return True
                else:
                    print(f"❌ 响应格式错误: {response_data}")
            except json.JSONDecodeError as e:
                print(f"❌ 响应JSON解析失败: {e}")
        else:
            print("❌ 未收到响应 (超时)")
            
            # 检查stderr
            try:
                stderr_output = process.stderr.read()
                if stderr_output:
                    print(f"STDERR: {stderr_output}")
            except:
                pass
        
        return False
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False
    
    finally:
        # 清理进程
        try:
            if process and process.poll() is None:
                process.terminate()
                process.wait(timeout=5)
        except:
            try:
                process.kill()
            except:
                pass

if __name__ == "__main__":
    success = test_direct_stdio()
    if success:
        print("\n🎉 stdio连接测试成功!")
    else:
        print("\n❌ stdio连接测试失败")
    
    sys.exit(0 if success else 1)